package com.by.hellospringboot.controller.advice;

import com.by.hellospringboot.controller.response.ErrorResponseBean;
import com.by.hellospringboot.exception.UnAuthorizedException;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@RestControllerAdvice
public class ControllerException {

    private ErrorResponseBean createErrorBean(int httpStatus, int code, String message, HttpServletRequest request) {
        ErrorResponseBean bean = new ErrorResponseBean();
        bean.setCode(code);
        bean.setHttpStatus(httpStatus);
        bean.setException(message);
        if (null != request) {
            bean.setPath(request.getRequestURI());
        }
        bean.setTimestamp(new Date());
        return bean;
    }

    @ResponseStatus(value = HttpStatus.UNAUTHORIZED) //返回数据时，http返回码
    @ExceptionHandler(UnAuthorizedException.class)
    public ErrorResponseBean handleUnAuthorizedException(UnAuthorizedException exception, HttpServletRequest request) {
        return createErrorBean(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), request);
    }

    /**
     * 处理服务器端数据库处理错误
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({SQLException.class, DataAccessException.class, DataAccessResourceFailureException.class,
            DataException.class, DataIntegrityViolationException.class})
    public ErrorResponseBean handleSQLException(HttpServletRequest request, Exception exception) {
        String message = exception.getLocalizedMessage();
        if (exception.getCause() instanceof ConstraintViolationException) {
            ConstraintViolationException e = (ConstraintViolationException) exception.getCause();
            message = e.getSQLException().getLocalizedMessage();
        }
        return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), message, request);
    }

    /**
     * 处理接口请求参数验证异常
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ErrorResponseBean handleValidException(HttpServletRequest request, MethodArgumentNotValidException exception) {
        StringBuilder message = new StringBuilder();
        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        for (ObjectError error :
                allErrors) {
            if (message.length() > 0) {
                message.append("、");
            }
            message.append(error.getDefaultMessage());
        }
        return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), message.toString(), request);
    }

    /**
     * 处理服务器端其他错误异常
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ErrorResponseBean handleOtherException(HttpServletRequest request, Exception exception) {
        return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage(), request);
    }

}
